import upmsMenuService from '@/core/upms/service/upmsMenuService'
import UpmsMenuAndAuthorityResponse from '@/core/upms/types/model/response/UpmsMenuAndAuthorityResponse'
import treeUtils from '@/core/utils/treeUtils'
import UpmsConstants from '@/core/oauth2/constants/UpmsConstants'
import UpmsMenuResponse from '../../../core/upms/types/model/response/UpmsMenuResponse'
import { MenuProps } from 'antd'
import React from 'react'

// 定义 menu 类型
export type MenuItem = Required<MenuProps>['items'][number]

class MenuUiService {
	getAllAdminAndToTreeByCurrentAccount = async (): Promise<MenuItem[]> => {
		const menus = await upmsMenuService.getMenus().then(this.toAntdMenuItemTypeTree)
		return menus
	}

	toAntdMenuItemTypeTree = (menuAndAuthorityResponses: UpmsMenuAndAuthorityResponse[]): MenuItem[] => {
		const menus: UpmsMenuResponse[] = menuAndAuthorityResponses.map(value => value.menu)
		return treeUtils.arrayToTree<UpmsMenuResponse, MenuItem>(menus, UpmsConstants.ROOT_PARENT_ID, this.itemTypeConverter)
	}

	getOpenKeys = (pathname: string): string[] => {
		return upmsMenuService.getMenuBreadcrumbByPath(pathname).map((value, index, array) => {
			return value.menu.uri
		})
	}

	private itemTypeConverter = (menu: UpmsMenuResponse): MenuItem => {
		return this.getMenuItem(menu.title, menu.uri, <i className={menu.icon}></i>)
	}
	getMenuItem = (
		label: React.ReactNode,
		key?: React.Key | null,
		icon?: React.ReactNode,
		children?: MenuItem[],
		type?: 'group',
	): MenuItem => {
		return {
			key,
			icon,
			children,
			label,
			type,
		} as MenuItem
	}
}

export default new MenuUiService()
